package com.googlecode.marrowboy.it;

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.maven.it.VerificationException;
import org.apache.maven.it.Verifier;

import com.googlecode.marrowboy.MarrowBoyMatchers;

public class AbstractITClass {

    private String marrowboyVersion = System.getProperty("marrowboy.version");

    protected void executeGoal(Verifier verifier, String goal) throws VerificationException {

        List<String> goals = getInitialGoals();
        goals.add(goal);
        executeGoals(verifier, goals);

    }

    private List<String> getInitialGoals() {

        ArrayList<String> goals = new ArrayList<String>();
        goals.add("-Dmarrowboy.version=" + marrowboyVersion);

        return goals;
    }

    @SuppressWarnings("unchecked")
    protected void executeGoals(Verifier verifier, List<String> goals) throws VerificationException {

        if (!verifier.getCliOptions().contains("-s")) {

            String settingsPath = System.getProperty("maven.settings.file");

            if (settingsPath.indexOf(' ') >= 0) {
                settingsPath = '"' + settingsPath + '"';
            }

            verifier.getCliOptions().add("-s");
            verifier.getCliOptions().add(settingsPath);

        }

        verifier.executeGoals(goals);
    }
    
    protected void assertFileContains(File reportFile, String substring) {

        try {
            String fileContent = IOUtils.toString(new FileInputStream(reportFile));
            assertThat(fileContent, containsString(substring));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    protected void assertFileHasMatch(File reportFile, String regex) {
        
        try {
            String fileContent = IOUtils.toString(new FileInputStream(reportFile));
            assertThat(fileContent, MarrowBoyMatchers.matchesRegex(regex));
            
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        
    }

}
